#!/usr/bin/python
# -*- coding: utf-8 -*-

#encodeing=utf-8

import sys,web


class Single(object):


	##私有方法:插入
	def __insertData(self,tablename,data):
		
		key=[]
		val=[]
		
		for i in data:
			key.append(i)
			val.append("'"+(data[i])+"'")

		if(len(key) >1):

			key1=",".join(key)
			val1=",".join(val)
		else:
			key1='' .join(key)
			val1='' .join(val)

		sql="insert into " + tablename + "(" + key1 + ") values ("+val1+")"

		return sql

	def insert(self,tablename,data):

		sql=self.__insertData(tablename,data)
		
		self.db.query(sql)
		
		

	#私有方法:更新
	def __updateData(self,tablename,data,condition):

		val=[]

		for i in range(len(data)):
			val.append( data.keys()[i] + " = '" + str(data.values()[i])+ "'" )

		val1=",".join(val)

		sql="update " + tablename + " set " +val1 + " where " + condition

		return sql
	
	def update(self,tablename,data,condition):

		sql=self.__updateData(tablename,data,condition)
		
		self.db.cursor().execute(sql)


	#私有方法:select
	def __select(self,tablename,columns,condition=None,orderby=None):

		col1=[]
		con1=[]
		con2=''
		orderby2=[]
		orderby3=''


		for v in columns:
			col1.append(  v  )

		col2=",".join(col1)

		if condition != None :

			count=len(condition)

			#for i in range(len(condition)):
			#	con1.append( condition.keys()[i] + "= '"+ str(condition.values()[i]) +"'" )
			for i in condition:
				con1.append( i +"='"+ (condition[i]+"'"))

			if count >1:
				con2="and " + " and " . join(con1)
			else:
				con2=" and " + ''.join(con1)
			
		
		if orderby !=None:
			
			count=len(orderby)

			for i in orderby:
				orderby2.append(i+" " + orderby[i] )
			if count >1:
				orderby3='order by ' + "," .join(orderby2)				
			else:
				orderby3='order by ' +''.join(orderby2)
					

		sql="select " + col2 + " from  " + tablename  + " where 1 " +  con2 + orderby3

		return sql
	
	def get_all(self,tablename,columns,condition=None,orderby=None):

		sql=self.__select(tablename,columns,condition,orderby)

		self.db.cursor().execute(sql)

		return self.db.fetchall()


	def get_row(self,tablename,columns,condition=None,orderby=None):

		sql=self.__select(tablename,columns,condition,orderby)

		self.db.execute(sql)

		return self.db.fetchone()


	def get_one(self,tablename,columns,condition=None):

		sql=self.__select(tablename,columns,condition)
		print sql	
		self.db.cursor.execute(sql)

		res=self.db.cursor.fetchone()

		if(res != None):
			return res[0]
		else:
			return 0
		
	
	def query(self,sql):

		self.db.execute(sql)

		return self.db.fetchall()

#a=Single()
#b=Single()
#
#data={}
#data['name']='tttttttt'
#data['age']=12
#
#a.update("users",data," id=1 ")
#
##col=[]
##col+=['name']
##col+=['age']

#col=('name','age')
#
#con={}
##con['id']=2
#
#
#c=a.get_all("users",col,False)
#
#for k,v in enumerate(c):
#	print v['name']
#print a.db
#print b.db
#print a==b
